﻿@page "/code share"
@using Tmp.Models
@inject DataContext DataContext
<RadzenCard >
    <RadzenText>
        分享你的代码给你的朋友，或者让你的朋友帮你解决你的代码，问题。
    </RadzenText>
</RadzenCard>
<div class="rz-p-sm-12 rz-text-align-center">
    <RadzenDropDown @bind-Value=@_language Data=@_languages TextProperty="Lang" ValueProperty="Highlight" AllowClear=true Placeholder="Select Language" Style="width: 100%; max-width: 400px;"
                    Change="@(async () => await JSRuntime.InvokeVoidAsync("highlightCode"))">
    </RadzenDropDown>
</div>
<RadzenTextArea Placeholder="请输入你的代码，选择一项语言不是必要的" @bind-Value="@_code" Rows="12" class="col-12" @oninput="StateHasChanged" Change="@(async () => await OnAfterRenderAsync(true))"></RadzenTextArea>
<RadzenStack Orientation="Orientation.Horizontal">
    <RadzenButton Shade="Shade.Light" Click="async () => Preview()" Text="预览" ButtonStyle="ButtonStyle.Success"/>
    <RadzenButton Shade="Shade.Light" Click="PutOn" Text="提交" ButtonStyle="ButtonStyle.Success"/>
</RadzenStack>

<style>

    @{ /* 使用C#代码块包裹媒体查询 */
            var mediaQuery = @"@media (max-width: 700px) { .wm { width: 100vw; } }
                                @media (min-width: 701px) {
      .wm {
        max-width: calc(100vw - 450px)!important;
      }
    }";

    }

    @mediaQuery

</style>
<RadzenCard>
    <pre class="wm col-12">
                                    <code class="hljs @_language" @key="_code.GetHashCode()">
                                        @_code
                                    </code>

                                </pre>


</RadzenCard>

@code{

    [Inject]
    public NavigationManager Manager { get; set; }

    private string? _language;

    private string? _code = @"";

    private IEnumerable<Language> _languages = Language.All();

    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    protected override async Task OnAfterRenderAsync(bool asFirstRender)
    {
        if (asFirstRender)
        {
            await JSRuntime.InvokeVoidAsync("highlightCode");
        }
    }


    private void PutOn()
    {
        var cipher = (_language + _code).GetHashCode().ToString();
        if (DataContext.SharedCodes.FirstOrDefault(lan => lan.Cipher == cipher) == null)
        {
            var language = DataContext.Languages.FirstOrDefault(l => l.Highlight == _language);
            if (language == null)
            {
                language = Language.FindLanguageByHighLight(_language);
            }
            language.Highlight ??= "auto";
            var sharedCode = new SharedCode()
            {
                Language = language,
                Cipher = cipher,
                Code = _code
            };
            DataContext.SharedCodes.Add(sharedCode);
            DataContext.SaveChanges();
        }
        Manager.NavigateTo($"/ShareResult/{cipher}?type=codes");
    }

    private async Task Preview()
    {
        await JSRuntime.InvokeVoidAsync("highlightCode");
    }

}